﻿using Role_el.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace Role_el.Controllers
{
    public class UsController : ApiController
    {
        /// <summary>
        /// 获取穿梭框数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IHttpActionResult GetRoles(int Id)
        {
            using (RolesDBEntities db = new RolesDBEntities())
            {
                var list = db.UserRoles.Where(t => t.UserId == Id).ToList();
                var Roleslist = db.Roles.Select(t => new { key = t.Id, label = t.Name }).ToList();
                if (list.Count > 0)
                {
                    var ss = "";
                    foreach (var item in list)
                    {
                        ss += Convert.ToString(item.Roled) + ",";
                    }

                    ss = ss.Substring(0, ss.Length - 1);
                    var mo = ss.Split(',').Select(x => int.Parse(x)).ToList();

                    return Json(new { code = 0, data = Roleslist, valus = mo, userId = Id });
                }
                else
                {
                    return Json(new { code = -1, data = Roleslist, valus = "", userId = Id });
                }

            }
        }
        /// <summary>
        /// 分配角色
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="movedKey"></param>
        /// <returns></returns>
        [HttpGet]
        public IHttpActionResult GetUsersRolesAdd(int userId, string movedKey)
        {
            using (RolesDBEntities db = new RolesDBEntities())
            {
                var mo = movedKey.Split(',').Select(x => int.Parse(x)).ToList();
                for (int i = 0; i < mo.Count; i++)
                {
                    UserRoles ur = new UserRoles() { UserId = userId, Roled = mo[i] };
                    db.UserRoles.Add(ur);
                }
                int n = db.SaveChanges();
                if (n > 0)
                {
                    return Json(new { code = 0, msg = "添加成功" });
                }
                else
                {
                    return Json(new { code = -1, msg = "添加失败" });
                }
            }
        }
        /// <summary>
        /// 移除角色
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="movedKey"></param>
        /// <returns></returns>
        [HttpGet]
        public IHttpActionResult GetUsersRolesDel(int userId, string movedKey)
        {
            using (RolesDBEntities db = new RolesDBEntities())
            {
                var mo = movedKey.Split(',').Select(x => int.Parse(x)).ToList();
                foreach (var item in mo)
                {
                    var ss = db.UserRoles.FirstOrDefault(t => t.Roled == item && t.UserId == userId);
                    db.UserRoles.Remove(ss);
                }
                int n = db.SaveChanges();
                if (n > 0)
                {
                    return Json(new { code = 0, msg = "删除成功" });
                }
                else
                {
                    return Json(new { code = -1, msg = "删除失败" });
                }
            }
        }
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="LoginName"></param>
        /// <returns></returns>
        [HttpGet]
        public IHttpActionResult GetUsList(int page,int limit,string LoginName,string IsLockout)
        {
            using (RolesDBEntities db = new RolesDBEntities())
            {
                var talist = db.Users.AsEnumerable();
                if (!string.IsNullOrEmpty(LoginName))
                {
                    talist = talist.Where(p => p.LoginName.Contains(LoginName));
                }
                if (!string.IsNullOrEmpty(IsLockout))
                {
                    talist = talist.Where(p => p.IsLockout==Convert.ToInt32(IsLockout));
                }
                var count = talist.Count();
                var list = talist.Select(p => new
                {
                    Id = p.Id,
                    LoginName = p.LoginName,
                    IsLockout = p.IsLockout,
                    LockTime = p.LockTime,
                    CreateTime=p.CreateTime,
                    ProtectMTel= p.ProtectMTel,
                    ProtectEmail=p.ProtectEmail,
                    Password= p.Password
                });
                return Json(new
                {
                    count = count,
                    data = list.OrderBy(p => p.Id).Skip((page-1)*limit).Take(limit).ToList()
                });
            }
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="us"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult AddUse([FromBody] Users us)
        {
            using (RolesDBEntities db = new RolesDBEntities())
            {
                Users r = db.Users.FirstOrDefault(p => p.LoginName == us.LoginName);
                if (r == null)
                {
                    db.Users.Add(us);
                    us.LastLoginTime = DateTime.Now;
                    us.CreateTime = DateTime.Now;
                    us.LockTime = null;
                    us.IsLockout = 0;
                    us.PsdWrongTime = 0;

                    int n = db.SaveChanges();
                    if (n > 0)
                    {
                        return Json(new
                        {
                            code = 0,
                            msg = "添加成功！"
                        });
                    }
                    else
                    {
                        return Json(new
                        {
                            code = -1,
                            msg = "添加失败！"
                        });
                    }
                }
                else
                {
                    return Json(new
                    {
                        code = -2,
                        msg = "该用户已存在！"
                    });
                }
            }
        }
        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="us"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult EditUse([FromBody] Users us)
        {
            using (RolesDBEntities db = new RolesDBEntities())
            {
                Users uslist = db.Users.SingleOrDefault(p => p.Id == us.Id);
                uslist.ProtectMTel = us.ProtectMTel;
                uslist.ProtectEmail = us.ProtectEmail;

                int n = db.SaveChanges();
                if (n > 0)
                {
                    return Json(new
                    {
                        code = 0,
                        msg = "修改成功！"
                    });
                }
                else
                {
                    return Json(new
                    {
                        code = -1,
                        msg = "修改失败！"
                    });
                }
            }
        }
        /// <summary>
        /// 重置
        /// </summary>
        /// <param name="us"></param>
        /// <returns></returns>
        public IHttpActionResult resetuser([FromBody] Users us)
        {
            using (RolesDBEntities db = new RolesDBEntities())
            {
                var ddd = db.Users.FirstOrDefault(p => p.Id == us.Id);
                if (ddd != null)
                {
                    ddd.Password = "000000";
                    int n = db.SaveChanges();
                    if (n > 0)
                    {
                        return Json(new { code = 0, msg = "重置成功！" });
                    }
                    else
                    {
                        return Json(new { code = -1, msg = "重置失败！" });
                    }
                }
                else
                {
                    return Json(new { code = -1, msg = "错误操作！" });
                }
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="us"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult DelUse([FromBody] Users us)
        {
            using (RolesDBEntities db = new RolesDBEntities())
            {
                var u = db.UserRoles.FirstOrDefault(p => p.UserId == us.Id);
                if (u == null)
                {
                    db.Entry<Users>(us).State = EntityState.Deleted;
                    int n = db.SaveChanges();
                    if (n > 0)
                    {
                        return Json(new { code = 0, msg = "删除成功！" });
                    }
                    else
                    {
                        return Json(new { code = -1, msg = "删除失败！" });
                    }
                }
                else
                {
                    return Json(new { code = -2, msg = "该用户拥有权限！" });
                }
            }
        }
        /// <summary>
        /// 状态锁定
        /// </summary>
        /// <param name="us"></param>
        /// <returns></returns>
        public IHttpActionResult updatestatus([FromBody]Users us)
        {
            using (RolesDBEntities db = new RolesDBEntities())
            {
                Users theuser = db.Users.FirstOrDefault(x => x.Id == us.Id);
                if (theuser.IsLockout == 0)
                {
                    theuser.IsLockout = 1;
                    theuser.LockTime = DateTime.Now;
                    int n = db.SaveChanges();
                    if (n > 0)
                    {
                        return Json(new { code = 0, msg = "锁定成功" });
                    }
                    else
                    {
                        return Json(new { code = 0, msg = "锁定失败" });

                    }
                }
                else
                {
                    theuser.IsLockout = 0;
                    theuser.LockTime = null;
                    int n = db.SaveChanges();
                    if (n > 0)
                    {
                        return Json(new { code = 0, msg = "解冻成功" });
                    }
                    else
                    {
                        return Json(new { code = 0, msg = "解冻失败" });

                    }
                }

            }

        }


    }
}
